<template>
  <a-modal v-model:open="ShowModalFlag" title="选择费用类别" @cancel="hideModal" @ok="hideModal" width="60vw">
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form" :model="queryForm">
      <a-form-item class="smart-query-form-item">
        <a-input v-model:value.trim="queryForm.category_name" placeholder="类别名称" autofocus />
      </a-form-item>

      <a-form-item class="smart-query-form-item">
        <a-button-group>
          <a-button type="primary" html-type="submit" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-table size="small" :dataSource="tableData" :columns="columns" :loading="tableLoading" rowKey="id" bordered :scroll="{ x: 'max-content', y: 350 }" :pagination="false" :showSorterTooltip="false" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange, preserveSelectedRowKeys: true }">
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="AddCategory(record)" type="link" v-privilege="'driver:edit'">编辑</a-button>
            <a-button @click="deleteData(record.id, record.category_name)" danger type="link" v-privilege="'driver:del'">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <div class="smart-query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <template #footer>
      <view style="display: flex; justify-content: space-between">
        <view>
          <a-button type="primary" @click="AddCategory" html-type="button">新增类别</a-button>
        </view>
        <view>
          <a-button @click="onClose" html-type="button">关闭</a-button>
          <a-button type="primary" @click="onSubmit" html-type="button">选择并关闭</a-button>
        </view>
      </view>
    </template>
  </a-modal>
  <a-modal v-model:open="open" :title="title" :confirm-loading="loading" @ok="submit" @cancel="cancel" width="550px">
    <a-form :model="form" :rules="rules" :label-col="{ sm: 4 }" ref="formRef">
      <a-form-item label="类别名称" name="category_name" required>
        <a-input v-model:value.trim="form.category_name" placeholder="请输入类别名称" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { errorSentry } from '@/lib/error-sentry'
import { useLoadingStore } from '@/store/modules/loading-store'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { expenseApi } from '@/api/business/finance/cost-api'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'

const loadingStore = useLoadingStore()
const emit = defineEmits(['confirm'])
const props = defineProps({
  disabled: {
    type: String
  }
})

const open = ref(false)
const title = ref('新增类别')
const loading = ref(false)
const formRef = ref()
const defaultForm = {
  category_name: ''
}
const form = ref(_.cloneDeep(defaultForm))
const rules = reactive({
  category_name: [{ required: true, message: '请输入类别名称', trigger: 'blur' }]
})
function AddCategory(rowData) {
  form.value = _.cloneDeep(defaultForm)
  if (rowData.id && !_.isEmpty(rowData)) {
    form.value = _.pick(rowData, ['id', ...Object.keys(defaultForm)])
  }
  open.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
function submit() {
  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        if (unref(form).id) {
          const data = {
            ...unref(form)
          }
          await expenseApi.editExpenseCategory(data)
        } else {
          const data = {
            ...unref(form)
          }
          await expenseApi.addExpenseCategory(data)
        }
        message.success('操作成功')
        cancel()
        queryData()
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      console.log('error', error)
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}
function cancel() {
  open.value = false
  formRef.value.resetFields()
}
// ---------------------------- 表格列 ----------------------------
const columns = ref([
  {
    title: '类别名称',
    dataIndex: 'category_name'
  },
  {
    title: '类别编码',
    dataIndex: 'id'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 100
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const { queryForm, tableData, tableLoading, total, onSearch, resetQuery, queryData, setQuery, deleteData } = useQuery({
  fetchDataApi: async (params) => {
    const res = await expenseApi.expenseCategoryList(params)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await expenseApi.delExpenseCategory({ id })
    return !!res
  },
  queryFormFilter: {
    category_name: ''
  },
  queryFormOp: {
    category_name: QUERY_FORM_OP['模糊查询']
  }
})
// ---------------------------- 重置 ----------------------------
onMounted(queryData)

// 选择表格行
const selectedRowKeyList = ref<number[]>([])
const selectedRowList = ref<any[]>([])

function onSelectChange(selectedRowKeys: number[], selectedRows: any[]) {
  selectedRowKeyList.value = selectedRowKeys
  selectedRowList.value = selectedRows
}

const ShowModalFlag = ref(false)
function hideModal() {
  ShowModalFlag.value = false
  resetQuery(false)
  selectedRowList.value = []
  selectedRowKeyList.value = []
}
function showModal() {
  ShowModalFlag.value = true
}

function onSubmit() {
  let isStockEnough = true
  if (isStockEnough) {
    if (selectedRowList.value.length > 0) {
      emit('confirm', selectedRowList.value)
    }
    hideModal()
  }
}

function onClose() {
  hideModal()
}

defineExpose({
  showModal,
  hideModal
})
</script>

<style lang="less" scoped>
.smart-query-form {
  --grid-column-col: 4;
  padding-left: 0;
  padding-right: 0;
}
</style>
